﻿using System;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKExcelFormTool.DataDefine;
using YJKExcelFormTool.Forms;
using YJKExcelFormTool.Kits;

namespace YJKExcelFormTool.Designer
{
	internal class ImportExcelTableDesigner
	{
		public ImportExcelTableDesigner(ExternalCommandData cmdData)
		{
			this.m_Revit = cmdData;
		}

		public Result Execute(ref string message)
		{
			TextNoteType fontType = this.GetFontType();
			double fontHeight = this.FontHeight(fontType);
			double fontWidthScale = this.FontWidthScale(fontType);
			using (ImportExcelTableForm importExcelTableForm = new ImportExcelTableForm(fontType.Name, fontHeight, fontWidthScale))
			{
				if (importExcelTableForm.ShowDialog() == DialogResult.OK)
				{
					TableInfos tableInfos = new TableInfos();
					tableInfos.Head = importExcelTableForm.SelectTableHead;
					tableInfos.SetFontSetting(fontType);
					return this.Drawing(ref message, tableInfos);
				}
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private TextNoteType GetFontType()
		{
			TextNoteType result = null;
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(this.m_Revit.Application.ActiveUIDocument.Document);
			filteredElementCollector.OfClass(typeof(TextNoteType));
			foreach (Element element in filteredElementCollector)
			{
				TextNoteType textNoteType = (TextNoteType)element;
				if (textNoteType.Name.CompareTo("仿宋_3.5mm") == 0)
				{
					result = textNoteType;
					break;
				}
			}
			return result;
		}

		private double FontHeight(TextNoteType fontSetting)
		{
			if (fontSetting == null)
			{
				return 2.5;
			}
			Parameter parameter = fontSetting.get_Parameter(BuiltInParameter.TEXT_SIZE);
			if (parameter == null)
			{
				throw new Exception("parameter 'TEXT_SIZE' is null.");
			}
			return AssistFunc.feetToMM(parameter.AsDouble());
		}

		private double FontWidthScale(TextNoteType fontSetting)
		{
			if (fontSetting == null)
			{
				return 0.7;
			}
			Parameter parameter = fontSetting.get_Parameter(BuiltInParameter.TEXT_WIDTH_SCALE);
			if (parameter == null)
			{
				throw new Exception("parameter 'TEXT_WIDTH_SCALE' is null.");
			}
			return AssistFunc.feetToMM(parameter.AsDouble());
		}

		private Result Drawing(ref string message, TableInfos tableInfos)
		{
			if (new ViewControler(this.m_Revit, ViewControler.TableViewType.TVT_IMPORTEXCELTABLE).CreateDraftingView(100) == ViewSelectResult.VSR_Cancel)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			TableDrawingToRevitKit tableDrawingToRevitKit = new TableDrawingToRevitKit(this.m_Revit, tableInfos, null);
			try
			{
				tableDrawingToRevitKit.Drawing(true);
			}
			catch
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private ExternalCommandData m_Revit;
	}
}
